package mark.tom.gear.app

import android.annotation.SuppressLint
import android.content.Context
import android.os.Process
import android.util.Log
import mark.tom.gear.BuildConfig
import mark.tom.gear.base.app.BaseApplication
import mark.tom.gear.base.callback.CallBack
import mark.tom.gear.base.utils.SystemUtil
import mark.tom.gear.utils.MultiDexUtil
import mark.tom.gear.view.activity.PreLoadDexActivity
import kotlin.system.exitProcess

/**
 * @Description: 自定义Application
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.app
 * @Date: 2020/12/31
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
open class GearApplication : BaseApplication() {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        if (null == base) {
            return
        }
        log(String.format("attachBaseContext-getPackageName: %s", base.packageName))
        log(String.format("attachBaseContext-getProcessName: %s", SystemUtil.getProcessName(base)))

        val isMainProcess = SystemUtil.isMainProcess(base)
        log(String.format("attachBaseContext-isMainProcess: %s", isMainProcess))

        //主进程并且vm不支持多dex的情况下才使用 MultiDex
        if (isMainProcess && !SystemUtil.isVMMultiDexCapable) {
            // 创建临时文件
            MultiDexUtil.createTmpFile(base)
            // 打开加载dex Activity进行加载
            MultiDexUtil.startMultiDexActivity(base, PreLoadDexActivity::class.java)
            // 检测临时文件 直至加载完成
            MultiDexUtil.checkUntilLoadDexSuccess(base, object: CallBack<Context, Any>{
                override fun onSuccess(param: Context) {
                    // 另一个进程以及加载 MultiDex，有缓存了，所以主进程再加载就很快了。
                    MultiDexUtil.install(param)
                }

                override fun onFail(param: Context) {
                    // 初始化失败 关闭当前进程
                    Process.killProcess(Process.myPid())
                    exitProcess(0)
                }
            })
        }
    }

    override fun onCreate() {
//        // init AndroidDevMetrics
//        if (isApplicationDebuggable()) {
//            val androidDevMetricsBuilder = AndroidDevMetrics.Builder(this)
//                .enableActivityMetrics(true)
//                .enableDagger2Metrics(false)
//                .showNotification(false)
//                .autoCancelNotification(false)
//            AndroidDevMetrics.initWith(androidDevMetricsBuilder)
//        }
        // Call Super
        super.onCreate()
    }

    override fun isApplicationDebuggable(): Boolean {
        return BuildConfig.DEBUG
    }

    @SuppressLint("LogNotTimber")
    private fun log(msg : String) {
        if (!isApplicationDebuggable()) {
            return
        }
        Log.d("CustomApplication", msg)
    }
}